package com.moon.app;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.beardedhen.androidbootstrap.BootstrapButton;
import com.moon.R;
import com.moon.common.AbstractActivity;
import com.moon.constants.MoonConstants;
import com.moon.model.UserJsonResult;
import com.moon.utils.HttpClientUtils;
import com.moon.utils.JacksonUtils;
import com.moon.utils.SharedPreferencesUtils;

/**
 * 登陆
 * 
 * @author paul
 * @date 2014年5月2日
 */
public class LoginActivity extends AbstractActivity {

    private static final String TAG = LoginActivity.class.getSimpleName();

    private EditText            email;
    private EditText            password;
    private TextView            textLoginRegister;
    private TextView            textLoginForgetPassword;

    private BootstrapButton     loginBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        
        email = (EditText) findViewById(R.id.editLoginAccount);
        password = (EditText) findViewById(R.id.editLoginPassword);

        email.setText(getUser().getEmail());

        //登录
        loginBtn = (BootstrapButton) findViewById(R.id.buttonLogin);
        loginBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                new LoginTask().execute(email.getText().toString(), password.getText().toString());
            }
        });

        //注册
        textLoginRegister = (TextView) findViewById(R.id.textLoginRegister);
        textLoginRegister.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
            }
        });

        //找回密码
        textLoginForgetPassword = (TextView) findViewById(R.id.textLoginForgetPassword);
        textLoginForgetPassword.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, FindPasswordActivity.class));
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        //getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private class LoginTask extends AsyncTask<String, String, Boolean> {
        String requeyUrl = "/mobile_user/dologin.do";

        @Override
        protected Boolean doInBackground(String... params) {
            try {
                //请求服务器
                List<NameValuePair> pairs = convertParams(params);
                String json = HttpClientUtils.post(MoonConstants.MOON_DOMAIN + requeyUrl, pairs);
                UserJsonResult result = JacksonUtils.fromJSON(json, UserJsonResult.class);
                if (result.isSuccess()) {
                    //写用户共享数据
                    writeSharedData(result);
                    //成功回登录
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    return true;
                } else {
                    if (StringUtils.isNotBlank(result.getMessage())) {
                        publishProgress(result.getMessage());
                    }
                    return false;
                }
            } catch (Exception e) {
                // 提示用户网络异常
                String message = getString(R.string.network_error);
                Log.e(TAG, message, e);
                publishProgress(message);
                return false;
            }
        }

        @Override
        protected void onProgressUpdate(String... values) {
            Toast.makeText(getApplicationContext(), values[0], Toast.LENGTH_SHORT).show();
        }

        /**
         * 组装request参数
         * 
         * @param params
         * @return
         */
        private List<NameValuePair> convertParams(String... params) {
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair(MoonConstants.USER_EMAIL, params[0]));
            pairs.add(new BasicNameValuePair(MoonConstants.USER_PASSWORK, params[1]));
            return pairs;
        }

        /**
         * 写入用户信息
         */
        private void writeSharedData(UserJsonResult result) {
            SharedPreferences shareDate = getSharedPreferences(
                    MoonConstants.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE);
            SharedPreferencesUtils.writeUserData(shareDate, result.getObject());
        }
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            //退回到桌面
            Intent home = new Intent(Intent.ACTION_MAIN);  

            home.addCategory(Intent.CATEGORY_HOME);   

            startActivity(home); 
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
